#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>

pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

void *SlaverCore(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        // 加锁
        pthread_mutex_lock(&g_mutex);
        // 一般条件变量是在加锁和解锁之间使用的
        pthread_cond_wait(&g_cond, &g_mutex);
        std::cout << "当前被叫醒的线程是：" << name << std::endl;
        // 加锁
        pthread_mutex_unlock(&g_mutex);
    }
}

void *MasterCore(void *args)
{
    sleep(1);// 让master线程休眠，主线程先运行
    std::cout << "master 开始工作..." << std::endl;
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_cond_signal(&g_cond); // 唤醒其中一个队列首部的线程
        // pthread_cond_broadcast(&g_cond); // 唤醒队列中所有线程
        std::cout << "master 唤醒一个线程..." << std::endl;
        sleep(1);
    }
}

void StartMaster(std::vector<pthread_t> *tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"Master Thread");
    if (n == 0)
    {
        std::cout << "create master success" << std::endl;
    }
    tidsptr->emplace_back(tid);
}

void StartSlaver(std::vector<pthread_t> *tidsptr, int threadnum = 3)
{
    for (int i = 0; i < threadnum; i++)
    {
        char *name = new char[64];
        snprintf(name, 64, "slaver-%d", i + 1);
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            std::cout << "create success: " << name << std::endl;
            tidsptr->emplace_back(tid);
        }
    }
}

void WaitThread(std::vector<pthread_t> &tids)
{
    for (auto &tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}

int main()
{
    std::vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids, 5);
    WaitThread(tids);
    return 0;
}